/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import com.cred.industries.core.database.DBConnectionManager;
import com.cred.industries.core.exceptions.ApplicationException;
import com.cred.industries.core.transferObj.result.ReturnCodes;
import com.cred.industries.platform.business.objects.ForgotPasswordBO;

public class ForgotPasswordMySQLDAO implements IForgotPasswordDAO {
	
	private static String TEMP_ID = "tempId";
	private static String CUSTOMERID = "customerId";
	private static String NEW_PASS = "newPass";
	private static String IS_VALID = "isValid";
	private static String TIME_ISSUED = "timeIssued";

	@Override
	public void insert(ForgotPasswordBO forgotPassBO) {
		
		// Setup the connection with the DB
		try (Connection connect = DBConnectionManager.getInstance().getConnection()) {
			insert(connect, forgotPassBO);
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to create DB connection temp password with " + forgotPassBO.getCustomerId() + " , " + forgotPassBO.getNewPassword());
		} 
	}

	@Override
	public void insert(Connection connect, ForgotPasswordBO forgotPassBO) {
			
		String sqlQuery = "INSERT INTO forgotpass VALUES(?, ?, ?, ?, ?)";
		try (PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery)) {
			
			preparedStatement.setString(1, forgotPassBO.getTempPasswordID());
			preparedStatement.setInt(2, forgotPassBO.getCustomerId());
			preparedStatement.setString(3, forgotPassBO.getNewPassword());
			preparedStatement.setBoolean(4, forgotPassBO.isValid());
			Timestamp issued = new Timestamp(forgotPassBO.getTimeIssued().getMillis());
			preparedStatement.setTimestamp(5, issued, Calendar.getInstance(TimeZone.getTimeZone("UTC")));
			
			int rowUpdated = preparedStatement.executeUpdate();
			if(rowUpdated == 0) {
				throw new ApplicationException(ReturnCodes.DATABASE_ERROR, "failed to create forgotPassBO with " + forgotPassBO.getCustomerId() +  " no rows updated");
			}
			
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to create forgotPass with " + forgotPassBO.getCustomerId() + " , " + forgotPassBO.getNewPassword());
		}
	}

	@Override
	public void update(ForgotPasswordBO forgotPassBO) {
		
		// Setup the connection with the DB
		try (Connection connect = DBConnectionManager.getInstance().getConnection()) {
			update(connect, forgotPassBO);
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to create DB connection update temp password with " + forgotPassBO.getCustomerId() + " , " + forgotPassBO.getNewPassword());
		} 
	}

	@Override
	public void update(Connection connect, ForgotPasswordBO forgotPassBO) {
		
		String sqlQuery = "UPDATE forgotpass SET " + IS_VALID + "=? WHERE " + TEMP_ID + " = ? ";
		try (PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery)) {
			
			preparedStatement.setBoolean(1, forgotPassBO.isValid());
			preparedStatement.setString(2, forgotPassBO.getTempPasswordID());
			
			int rowUpdated = preparedStatement.executeUpdate();
			if(rowUpdated == 0) {
				throw new ApplicationException(ReturnCodes.DATABASE_ERROR, "failed to update forgotPassBO with " + forgotPassBO.getCustomerId() +  " no rows updated");
			}
			
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to update forgotPass with " + forgotPassBO.getCustomerId() + " , " + forgotPassBO.getNewPassword());
		}
	}

	@Override
	public ForgotPasswordBO findById(String forgotPassID) {
		
		String sqlQuery = "SELECT * FROM forgotpass WHERE " + TEMP_ID + " = ? ";
		try (Connection connect = DBConnectionManager.getInstance().getConnection();
				PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery);) {
			
			preparedStatement.setString(1, forgotPassID);
			
			try (ResultSet resultSet = preparedStatement.executeQuery()) {
			
				if(resultSet.next()) {
					
					String tempId = resultSet.getString(TEMP_ID);
					int custId = resultSet.getInt(CUSTOMERID);
					String newPass = resultSet.getString(NEW_PASS);
					boolean isValid = resultSet.getBoolean(IS_VALID);
					Timestamp issued = resultSet.getTimestamp(TIME_ISSUED, Calendar.getInstance(TimeZone.getTimeZone("UTC")));
					
					return new ForgotPasswordBO(tempId
												, custId
												, newPass
												, isValid
												, new DateTime(issued, DateTimeZone.UTC));
				}
			}
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to find forgotPass with " + forgotPassID);
		}
		return null;
	}

	@Override
	public boolean delete(ForgotPasswordBO forgotPassBO) {
		
		String sqlQuery = "DELETE FROM forgotpass WHERE " + TEMP_ID + " = ? ";
		
		// Setup the connection with the DB
		try (Connection connect = DBConnectionManager.getInstance().getConnection();
				PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery)) {

			preparedStatement.setString(1, forgotPassBO.getTempPasswordID());
			
			int rowsDeleted = preparedStatement.executeUpdate();
			
			if(rowsDeleted > 0)
				return true;

		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to update forgotPass with " + forgotPassBO.getCustomerId() + " , " + forgotPassBO.getNewPassword());
		}
		
		return false;
	}

}
